## Script (Python) "tree_diagram"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##title=Generate concept tree diagram
##parameters=top=None,doubleSpacing=False

def uncleBelow(level,pos,tree):
    ''' used to detect an "uncle" below current item
        ("uncle" is a sibling of the parent)
    '''
    found = False
    uncleLevel = level-1
    for item in tree[pos+1:]:
        if item['level'] < uncleLevel: break
        if item['level'] == uncleLevel:
            found = True
            break
    return found

H = u'\u2500'.encode('utf8') # ─ BOX DRAWINGS LIGHT HORIZONTAL
I = u'\u2502'.encode('utf8') # │ BOX DRAWINGS LIGHT VERTICAL
T = u'\u251C'.encode('utf8') # ├ BOX DRAWINGS LIGHT VERTICAL AND RIGHT
L = u'\u2514'.encode('utf8') #     └ BOX DRAWINGS LIGHT UP AND RIGHT
X = '&nbsp;'

if top is None: top = context
tree = top.tree()
prefix = []
for i,item in enumerate(tree):
    if i==0: prev = None
    else:    prev = tree[i-1]
    if i==len(tree)-1: next = None
    else:              next = tree[i+1]
    if prev:
        if prev['level'] < item['level']:
            if next and item['siblingsBelow']:
                prefix.append(T+H+H)
            else:
                prefix.append(L+H+H)
            if len(prefix) > 1:
                if uncleBelow(item['level'],i,tree):
                    prefix[-2] = I+X+X
                else:
                    prefix[-2] = X+X+X
        else:
            dedent = prev['level'] - item['level']
            if dedent:
                prefix = prefix[:-dedent]
            if prefix:
                if next and item['siblingsBelow']:  
                    prefix[-1] = T+H+H
                else:
                    prefix[-1] = L+H+H
    prefixStr = ''.join(prefix)
    if doubleSpacing:
        print prefixStr.replace(T,I).replace(L,I).replace(H,X)
    html = '<a href="%s">%s</a>' % (item['url'], item['title'])
    print prefixStr + html
return printed